package easy;

public class Question9 {

    public static void main(String[] args) {
        Question9 question9 = new Question9();
        System.out.println(question9.isPalindrome(1000440001) ? "true" : "false");
        System.out.println(question9.isPalindrome(121) ? "true" : "false");
        System.out.println(question9.isPalindrome(1000220001) ? "true" : "false");
        System.out.println(question9.isPalindrome(-121) ? "true" : "false");
        System.out.println(question9.isPalindrome(10) ? "true" : "false");
        System.out.println(question9.isPalindrome(-101) ? "true" : "false");
    }

    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        } else if (x <= 9) {
            return true;
        } else {
            int length = 1 + (int) Math.log10(x);
            return reverse(getHalf(x, length)) == getRest(x, length / 2);
        }
    }

    public int getRest(int x, int k) {
        return x % ((int) Math.pow(10, k));
    }

    public int getHalf(int x, int k) {
        return x / ((int) Math.pow(10, k - k / 2));
    }

    // 此处的reverse()只能反转非负数
    public int reverse(int x) {
        int result = 0;
        try {
            while (x != 0) {
                if (result > (Integer.MAX_VALUE - x % 10) / 10) {
                    throw new RuntimeException();
                }
                result = result * 10 + x % 10;
                x /= 10;
            }
        } catch (Exception ignored) {
            return 0;
        }
        return result;
    }
}
